//
//  ConfirmViewController.m
//  SecretAlbums
//
//  Created by BabyFinancial on 15/6/18.
//  Copyright (c) 2015年 BabyFinancial. All rights reserved.
//

#import "ConfirmViewController.h"
#import "SecretAlbumsLogic.h"
#import "AppDelegate.h"
#import "DotsView.h"
#import "Masonry.h"
#import "SecretAlbumsConst.h"

#define CircleButtonDiameter Adapter_X(74.0f)
#define Spacing (CircleButtonDiameter + Adapter_X(18.0f))
#define OffsetOfY Adapter_Y(-14.0f)

@interface ConfirmViewController () <DotsViewDelegate, CircleButtonDelegate>

@property (nonatomic, strong) UILabel *titleLable;
@property (nonatomic, strong) UIColor *circleBtnTitleColor;
@property (nonatomic, strong) DotsView *dotsView;
@property (nonatomic, strong) UIButton *actionBtn;
@property (nonatomic, strong) NSMutableArray *circleBtnArray;

@end

@implementation ConfirmViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIView *backgroundView = [[UIView alloc] init];
    backgroundView.backgroundColor = [UIColor colorWithRed:0.2f green:0.2f blue:0.2f alpha:0.6f];
    [self.view addSubview:backgroundView];
    [self.view sendSubviewToBack:backgroundView];
    
    [backgroundView setTranslatesAutoresizingMaskIntoConstraints:NO];
    [backgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    // 添加NumberpadView并设置
    self.numberpadView = [[UIView alloc] init];
    self.numberpadView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.numberpadView];
    
    [self.numberpadView setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self.numberpadView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(MAX(self.view.bounds.size.width, self.view.bounds.size.height), MAX(self.view.bounds.size.width, self.view.bounds.size.height)));
    }];
    
    // 添加NumberpadView中得控件
    [self setupNumberpad];
    
    // 设置NumberpadView的颜色
    self.numberpadView.tintColor = SAColor(239, 125, 38);
    self.circleBtnTitleColor = [UIColor whiteColor];
    
    // 设置标题文本
    self.titleLable.text = NSLocalizedString(@"EnterCurrentPassword", nil);
    self.titleLable.textColor = [UIColor whiteColor];

    // 设置Cancel按钮
    [self.actionBtn setTitle:NSLocalizedString(@"Cancel", nil) forState:UIControlStateNormal];
    [self.actionBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.actionBtn addTarget:self action:@selector(cancelBtnOnclick:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)setupBackgroundWithImage:(UIImage *)image
{
    self.view.backgroundColor = [UIColor colorWithPatternImage:[self blur:image]];
}

- (BOOL)shouldAutorotate
{
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}

- (void)setCircleBtnTitleColor:(UIColor *)circleBtnTitleColor
{
    _circleBtnTitleColor = circleBtnTitleColor;
    
    for (int i=0; i<self.circleBtnArray.count; i++) {
        CircleButton *btn = self.circleBtnArray[i];
        btn.titleLabel.textColor = self.circleBtnTitleColor;
        btn.cancelLayer.strokeColor = self.circleBtnTitleColor.CGColor;
    }
}

#pragma mark - CircleButtonDelegate

- (void)touchCircleButton:(CircleButton *)circleButton
{
    [self.dotsView operateFromCircleButton:circleButton];
}

#pragma mark - 私有方法

- (void)setupNumberpad
{
    self.circleBtnArray = [NSMutableArray array];
    
    // 添加提示文本
    self.titleLable = [UILabel new];
    [self.titleLable setTranslatesAutoresizingMaskIntoConstraints:NO];
    self.titleLable.font = [UIFont systemFontOfSize:Adapter_X(22.0f)];
    [self.numberpadView addSubview:self.titleLable];
    
    [self.titleLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.numberpadView).centerOffset(CGPointMake(0, Iphone4OrOtherAdapter_Y(-190, -210)));
    }];
    
    // 添加数字按钮
    for (int i=0; i<10; i++) {
        CircleButton *btn = [[CircleButton alloc] initWithType:CircleButtonDefault];
        [btn setTranslatesAutoresizingMaskIntoConstraints:NO];
        btn.titleLabel.text = [NSString stringWithFormat:@"%d", i];
        btn.delegate = self;
        [self.numberpadView addSubview:btn];
        [self.circleBtnArray addObject:btn];
        
        if (0 == i) {
            [btn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.size.mas_equalTo(CGSizeMake(CircleButtonDiameter, CircleButtonDiameter));
                make.centerX.equalTo(self.numberpadView.mas_centerX);
                make.centerY.equalTo(self.numberpadView.mas_centerY).offset(2 * Spacing + OffsetOfY);
            }];
        } else {
            [btn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.size.mas_equalTo(CGSizeMake(CircleButtonDiameter, CircleButtonDiameter));
                make.centerX.equalTo(self.numberpadView.mas_centerX).offset(-Spacing + ((i-1)%3)*Spacing);
                make.centerY.equalTo(self.numberpadView.mas_centerY).offset(-Spacing + ((i-1)/3)*Spacing + OffsetOfY);
            }];
        }
    }
    
    // 添加取消按钮
    CircleButton *btn = [[CircleButton alloc] initWithType:CircleButtonCancel];
    [btn setTranslatesAutoresizingMaskIntoConstraints:NO];
    btn.delegate = self;
    [self.numberpadView addSubview:btn];
    [self.circleBtnArray addObject:btn];
    
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(CircleButtonDiameter, CircleButtonDiameter));
        make.centerX.equalTo(self.numberpadView.mas_centerX).offset(Spacing);
        make.centerY.equalTo(self.numberpadView.mas_centerY).offset(2 * Spacing + OffsetOfY);
    }];
    
    // 添加dot
    self.dotsView = [[DotsView alloc] initWithAmount:6];
    [self.dotsView setTranslatesAutoresizingMaskIntoConstraints:NO];
    self.dotsView.delegate = self;
    [self.numberpadView addSubview:self.dotsView];
    
    [self.dotsView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.numberpadView).centerOffset(CGPointMake(0, Iphone4OrOtherAdapter_Y(-160, -170)));
    }];
    
    // 添加action按钮
    self.actionBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.actionBtn setTranslatesAutoresizingMaskIntoConstraints:NO];
    self.actionBtn.titleLabel.font = [UIFont systemFontOfSize:Adapter_X(18.0f)];
    [self.numberpadView addSubview:self.actionBtn];
    
    [self.actionBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.numberpadView.mas_centerX).offset(Adapter_X(-100));
        make.centerY.equalTo(self.numberpadView.mas_centerY).offset(Iphone4OrOtherAdapter_Y(200, 244));
    }];
}

- (void)cancelBtnOnclick:(UIButton *)button
{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate logoutWithAnimation:NO];
}

- (UIImage*)blur:(UIImage*)theImage
{
    // create our blurred image
    CIContext *context = [CIContext contextWithOptions:nil];
    CIImage *inputImage = [CIImage imageWithCGImage:theImage.CGImage];
    
    CIFilter *affineClampFilter = [CIFilter filterWithName:@"CIAffineClamp"];
    CGAffineTransform xform = CGAffineTransformMakeScale(1.0, 1.0);
    [affineClampFilter setValue:inputImage forKey:kCIInputImageKey];
    [affineClampFilter setValue:[NSValue valueWithBytes:&xform
                                               objCType:@encode(CGAffineTransform)]
                         forKey:@"inputTransform"];
    
    CIImage *extendedImage = [affineClampFilter valueForKey:kCIOutputImageKey];
    
    // setting up Gaussian Blur (could use one of many filters offered by Core Image)
    CIFilter *blurFilter = [CIFilter filterWithName:@"CIGaussianBlur"];
    [blurFilter setValue:extendedImage forKey:kCIInputImageKey];
    [blurFilter setValue:[NSNumber numberWithFloat:25.0f] forKey:@"inputRadius"];
    CIImage *result = [blurFilter valueForKey:kCIOutputImageKey];
    
    // CIGaussianBlur has a tendency to shrink the image a little,
    // this ensures it matches up exactly to the bounds of our original image
    CGImageRef cgImage = [context createCGImage:result fromRect:[inputImage extent]];
    
    UIImage *returnImage = [UIImage imageWithCGImage:cgImage];
    //create a UIImage for this function to "return" so that ARC can manage the memory of the blur...
    //ARC can't manage CGImageRefs so we need to release it before this function "returns" and ends.
    CGImageRelease(cgImage);//release CGImageRef because ARC doesn't manage this on its own.
    
    return returnImage;
}

#pragma mark - DotsViewDelegate

- (BOOL)verifyPassword:(NSString *)password FromDotsView:(DotsView *)dotsView
{
    if ([[SecretAlbumsLogic currentAlbumID] isEqualToString:password]) {
        return YES;
    } else {
        self.titleLable.text = NSLocalizedString(@"PasswordError", nil);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.titleLable.text = NSLocalizedString(@"EnterCurrentPassword", nil);
        });
        
        return NO;
    }
}

- (void)successPassword:(NSString *)password FromDotsView:(DotsView *)dotsView
{
    // 密码验证成功，关闭页面
    [self.dotsView cleanPassWord];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(successConfirmViewController:)]) {
        [self.delegate successConfirmViewController:self];
    }
}

@end
